<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\LayuiController;
use App\Jobs\ExportData;
use App\Models\AccountLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use SuperClosure\Serializer;

class BalanceChangeController extends Controller
{
    /**
     * 列表页视图
     * @name index
     * @param \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/23 10:23
     */
    public function index(){

        return view('Admin.balanceChange.index');
    }

    /**
     * 列表页表格数据方法
     * @name table
     * @param array
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/21 9:43
     */
    public function table(Request $request){

        $payload = $request->all();

        $preData = AccountLog::with(['userInfo'])
            ->when($keyword = array_get($payload,'keyword'),function($query)use($keyword){
                $query->where(function($query)use($keyword){
                    $query->whereHas('userInfo',function($query)use($keyword){
                        $query->where('number', 'like', "%$keyword%")
                            ->orWhere('realname','like', "%$keyword%")
                            ->orWhere('nickname','like', "%$keyword%")
                            ->orWhere('phone','like', "%$keyword%");
                    });
                });
            })
            ->where('account_type',AccountLog::EIGHT_BALANCE)
            ->where('status',AccountLog::SUCCESS)
            ->orderBy('id','desc')
            ->paginate($request->get('limit',30));

        $data = $preData->map(function($item){
            return [
                'id'                    => $item->id,
                'realname'              => $item->userInfo->realname ?? '',
                'nickname'              => $item->userInfo->nickname ?? '',
                'number'                => $item->userInfo->number ?? '',
                'phone'                 => $item->userInfo->phone ?? '',
                'avatar'                => $item->userInfo->avatar ?? '',
                'money'                 => numberFormat($item->money),
                'balance'               => numberFormat($item->balance),
                'type'                  => AccountLog::TYPE[$item->type] ?? '',
                'created_at'            => $item->created_at,
                'trade_no'              => $item->trade_no
            ];
        });

        return LayuiController::tableJson($data,0,$preData->total());
    }

    /**
     * 导出操作
     * @name export
     * @param \Illuminate\Http\JsonResponse
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/29 9:12
     */
    public function export(Request $request){
        /* 1 获取查询条件 */
        $payload = $request->all();

        $filename = $request->input('filename','demo.csv');

        $filename = rtrim($filename,'.csv').'.csv';

        if(Storage::disk('exports')->exists($filename))
            return $this->getResponse('文件已存在，请重新输入',[],302,route('balanceChange.index'));

        /* 2 查询准备 */
        $query = function() use($payload) {
            return AccountLog::with(['userInfo'])
                ->when($keyword = array_get($payload,'keyword'),function($query)use($keyword){
                    $query->where(function($query)use($keyword){
                        $query->whereHas('userInfo',function($query)use($keyword){
                            $query->where('number', 'like', "%$keyword%")
                                ->orWhere('realname','like', "%$keyword%")
                                ->orWhere('nickname','like', "%$keyword%")
                                ->orWhere('phone','like', "%$keyword%");
                        });
                    });
                })
                ->where('account_type',AccountLog::EIGHT_BALANCE)
                ->where('status',AccountLog::SUCCESS)
                ->orderBy('id','desc');
        };

        /* 3 数据回调处理 */
        $call = function($item){
            return [
                'realname'              => $item->userInfo->realname,
                'phone'                 => $item->userInfo->phone,
                'money'                 => $item->money,
                'balance'               => $item->balance,
                'type'                  => AccountLog::TYPE[$item->type],
                'created_at'            => $item->created_at,
                'trade_no'              => $item->trade_no
            ];
        };

        /* 4 定义文件头 */
        $header = [
            'created_at'            => '变动时间',
            'type'                  => '变动类型',
            'realname'              => '会员姓名',
            'phone'                 => '会员手机号码',
            'money'                 => '变动金额',
            'balance'               => '变动后余额',
            'trade_no'              => '订单编号',
        ];

        /* 5 插入队列 */

        /* 闭包序列化处理 */
        $serializer = new Serializer();

        dispatch(new ExportData($header,$serializer->serialize($query),$serializer->serialize($call),$filename));

        return $this->getResponse('已加入导出队列',[],200,route('balanceChange.index'));
    }
}
